﻿using System;
using System.Collections.Generic;
using System.Text;

namespace KnBinarySerializer.Data
{
    internal class DataSetFormatter : IFormatter
    {
        public Type GetHandleType()
        {
            return typeof(System.Data.DataSet);
        }

        public byte GetKey()
        {
            return 31;
        }

        public bool IsFixLen()
        {
            return false;
        }

        public object ReadBytes(BinarySerializeManager serial, int maxLen, Type type)
        {
            System.Data.DataSet dataSet = new System.Data.DataSet();
            dataSet.Namespace = serial.DeSerializeObject<string>();
            dataSet.DataSetName = serial.DeSerializeObject<string>();
            int cnt = serial.ReadInt();
            for (int i = 0; i < cnt; i++)
            {
                System.Data.DataTable table = serial.DeSerializeObject<System.Data.DataTable>();
                dataSet.Tables.Add(table);
            }
            return dataSet;
        }

        public int WriteBytes(BinarySerializeManager serial, object obj)
        {
            System.Data.DataSet dataSet = (System.Data.DataSet)obj;
            //long start = serial.GetPosition();
            serial.SerializeObject(dataSet.Namespace);
            serial.SerializeObject(dataSet.DataSetName);
            serial.Write(dataSet.Tables.Count);
            foreach (System.Data.DataTable table in dataSet.Tables)
            {
                serial.SerializeObject(table);
            }
            //return serial.GetLength(start);
            return -1;
        }
    }
}
